<template>
    <div class="layout-padding">
        <el-form :inline="true" ref="queryRef" :model="queryParams" label-width="100px">
            <el-row>
                <!-- <el-col :span="5">
                    <el-form-item label="区段：">
                        <el-tree-select v-model="queryParams.section" :data="dataSource" clearable
                            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                            :render-after-expand="false" check-strictly @change="treeChange">
                        </el-tree-select>
                    </el-form-item>
                </el-col> -->
                <el-col :span="6">
                    <el-form-item label="工区：">
                        <el-tree-select v-model="queryParams.workAreaId" :data="dataSource"
                            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                            :render-after-expand="false" check-strictly clearable>
                        </el-tree-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="设备名称：">
                        <el-input placeholder="请输入内容" v-model="queryParams.device" clearable>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
                        <el-button type="primary" @click="handleImport">导入</el-button>
                        <el-button type="primary" @click="handleExport">导出</el-button>
                        <el-button type="primary" @click="handleAdd">新增</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            
            
            
            
        </el-form>

        <el-table v-loading="loading" :data="list">
            <el-table-column type="index" width="50" label="序号"></el-table-column>
            <el-table-column label="地点" align="center" prop="location" />
            <el-table-column label="设备名称" align="center" prop="device" />
            <el-table-column label="数量" align="center" prop="amount" />
            <el-table-column label="型号" align="center" prop="type" />
            <el-table-column label="联系方式" align="center" prop="contactsPhone" />
            <el-table-column label="联系人" align="center" prop="contacts" />
            <el-table-column label="关联工区" align="center" prop="workArea" />
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">编辑</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 详情对话框 -->
        <el-dialog :title="title" v-model="open" width="780px" append-to-body>
            <el-form ref="configRef" :model="form" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="地点：" prop="location">
                            <el-input v-model="form.location" placeholder="请输入参数" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="设备名称：" prop="device">
                            <el-input v-model="form.device" placeholder="请输入参数" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="数量：" prop="amount">
                            <el-input v-model="form.amount" placeholder="请输入参数" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="型号：" prop="type">
                            <el-input v-model="form.type" placeholder="请输入参数" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="联系方式：" prop="contactsPhone">
                            <el-input v-model="form.contactsPhone" placeholder="请输入参数" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系人：" prop="contacts">
                            <el-input v-model="form.contacts" placeholder="请输入参数" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="关联工区" prop="workAreaId">
                    <!-- <el-input v-model="form.workAreaId" type="textarea" placeholder="请输入" /> -->
                    <el-tree-select v-model="form.workAreaIds" :data="dataSource" multiple
                        :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" :render-after-expand="false"
                        check-strictly>
                        </el-tree-select>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">保存</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    </div>
</template>

<script setup>
import { listEquipment, getEquipment, addEquipment, updateEquipment, delEquipment } from "@/api/system/instrument.js";
import { getTreeList, getDeptBy } from "@/api/work";
const { proxy } = getCurrentInstance();
const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        submited: true,
        workAreaId:''
    },
    rules: {
        // section: [{ required: true, message: "参数名称不能为空", trigger: "blur" }],
    }
});
const { queryParams, form, rules } = toRefs(data);

const loading = ref(true);
const list = ref([]);
const total = ref(0);
const open = ref(false);
const title = ref("路外大型器械");

//区段数据
const dataSource = ref([])
const dataSourceArea = ref([])
function getTree() {
    getTreeList().then(res => {
        dataSource.value = res.data
    })
}
getTree()

function treeChange(id) {
    dataSourceArea.value = []
    queryParams.value.workAreaId = ''
    form.value.workArea = ''
    if(id == null || id == undefined || id == ''){
        return
    }
    getDeptBy({
        parentId: id
    }).then(res => {
        dataSourceArea.value = res.data
    })
}



/** 查询公告列表 */
function getList() {
    loading.value = true;
    listEquipment(queryParams.value).then(response => {
        list.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}


/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}


/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加路外大型器械";
}
import { getToken } from '@/utils/auth'
  /*** 导入参数 */
  const upload = reactive({
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: '',
      // 是否禁用上传
      isUploading: false,
      // 是否更新已经存在的用户数据
      updateSupport: 0,
      // 设置上传的请求头部
      headers: { Authorization: 'Bearer ' + getToken() },
      // 上传的地址
      url: import.meta.env.VITE_APP_BASE_API + '/sjgtw-emergency/equipment/importData',
  })
  /** 导入按钮操作 */
  function handleImport() {
      upload.title = '导入'
      upload.open = true
  }
  /** 提交上传文件 */
function submitFileForm() {
    proxy.$refs['uploadRef'].submit()
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true
}
  /** 下载模板操作 */
  function importTemplate() {
      proxy.download('sjgtw-emergency/equipment/downloadTemplate', {}, `template_${new Date().getTime()}.xlsx`)
  }
  /** 文件上传成功处理 */
  const handleFileSuccess = (response, file, fileList) => {
      upload.open = false
      upload.isUploading = false
      proxy.$refs['uploadRef'].handleRemove(file)
      if (response.code == 200) {
          proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      } else {
          proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.data + '</div>', '导入失败', { dangerouslyUseHTMLString: true })
      }
      getList()
  }

/** 导出按钮操作 */
function handleExport() {
    proxy.download("sjgtw-emergency/equipment/export", {
    ...queryParams.value, 
    }, `路外大型器械${new Date().getTime()}.xlsx`);
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const id = row.id;
    getEquipment(id).then(response => {
        response.data.workAreaIds = (response.data.workAreaId + "").split(',');
        response.data.workAreaIds = response.data.workAreaIds.map(item=>{
            return item * 1
        })
        form.value = response.data;
        open.value = true;
        title.value = "修改路外大型器械";
    });

}

/** 删除按钮操作 */
function handleDelete(row) {
    const id = row.id;
    proxy.$modal.confirm('是否确认删除区段id为"' + id + '"的数据项？').then(function () {
        return delEquipment(id);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}

/** 取消按钮 */
function cancel() {
    open.value = false;
    reset();
}

/** 表单重置 */
function reset() {
    form.value = {
        workAreaIds: [],
    };
    proxy.resetForm("configRef");
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["configRef"].validate(valid => {
        if (valid) {
            form.value.workAreaId = form.value.workAreaIds.join(',');
            form.value.submited = 1;
            if (form.value.id != undefined) {
                updateEquipment(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addEquipment(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

getList();
</script>

<style lang="scss" scoped>
.layout-padding {
    padding: 10px;
}
</style>
